#include "../includes/IPC.h"
#include <iostream>

int main() {
    IpcServer& server = IpcServer::getInstance("/tmp/test_ipc.sock");
    
    std::cout << "Server starting..." << std::endl;
    
    while (true) {
        int client_fd = server.accept_conn();
        if (client_fd == -1) {
            std::cerr << "Accept failed" << std::endl;
            continue;
        }
        
        std::cout << "Client connected" << std::endl;
        
        // 与客户端进行双向通信
        char recv_buf[1024];
        char send_buf[1024];
        
        while (true) {
            // 接收客户端消息
            int recv_size = server.receive_data(client_fd, 1024, recv_buf);
            if (recv_size <= 0) {
                break; // 客户端断开连接
            }
            
            recv_buf[recv_size] = '\0';
            std::cout << "Server received: " << recv_buf << std::endl;
            
            // 回复客户端
            std::string response = "Echo: ";
            response += recv_buf;
            strcpy(send_buf, response.c_str());
            
            int send_size = server.send_data(client_fd, response.length(), send_buf);
            if (send_size <= 0) {
                break; // 发送失败
            }
            
            std::cout << "Server sent: " << send_buf << std::endl;
        }
        
        close(client_fd);
        std::cout << "Client disconnected" << std::endl;
    }
    
    return 0;
}